from django.db import models
from django.db.models import Manager
from django.contrib.contenttypes.models import ContentType
from utils.secret import encrypt, random_key
import datetime


# cannot import name 'UserModel' from 'auth_app.models'
class BaseModel(models.Model):
    id = models.AutoField(primary_key=True)
    create_time = models.DateTimeField(auto_now_add=True)
    update_time = models.DateTimeField(auto_now=True)

    class Meta:
        abstract = True


class UserManager(Manager):

    def _change_token_key(self, auth_obj):
        # 修改User中token_key
        # 返回一个User对象
        auth_obj.token_key = random_key()
        auth_obj.save()
        return auth_obj

    def _encrypt_pwd(self, pwd):
        return encrypt(pwd)

    def create_super_user(self, **kwargs):
        kwargs['usr_pwd'] = self._encrypt_pwd(pwd=kwargs['usr_pwd'])
        kwargs['is_super'] = True
        kwargs['is_valid'] = True
        author = UserModel.objects.create(**kwargs)
        return author

    def create_user(self, **kwargs):
        kwargs['usr_pwd'] = self._encrypt_pwd(pwd=kwargs['usr_pwd'])
        kwargs['is_valid'] = True
        author = UserModel.objects.create(**kwargs)
        return author

    def check_pwd(self, id, pwd):
        author_obj = UserModel.objects.get(id=id)
        return author_obj.usr_pwd == self._encrypt_pwd(pwd)

    def set_pwd(self, id, new_pwd):
        author_obj = UserModel.objects.get(id=id)
        author_obj.usr_pwd = self._encrypt_pwd(new_pwd)
        author_obj.save()
        return author_obj

    def login(self, **kwargs):
        status, instance, message = False, None, '用户名或者密码错误'  # 登陆状态,登录信息
        author_qs = UserModel.objects.filter(usr_name=kwargs['usr_name'])
        if author_qs:
            author_obj = author_qs[0]
            if self._encrypt_pwd(kwargs['usr_pwd']) == author_obj.usr_pwd:
                self._change_token_key(author_obj)
                author_obj.last_login = datetime.datetime.now()
                author_obj.save()
                status, instance, message = True, author_obj, '登陆成功'
        return status, instance, message

    def logout(self, id):
        obj = UserModel.objects.get(id=id)
        self._change_token_key(obj)
        return obj


class UserModel(BaseModel):
    verbose_name = '用户管理'

    usr_name = models.CharField(max_length=50, unique=True)
    usr_pwd = models.CharField(max_length=200)
    usr_phone = models.IntegerField(null=True)
    usr_mail = models.EmailField(null=True)
    is_valid = models.BooleanField(default=False)
    is_super = models.BooleanField(default=False)
    last_login = models.DateTimeField(null=True)
    token_key = models.CharField(max_length=255, null=True, default=None)

    objects = UserManager()

    class Meta:
        db_table = 'auth_user'


class RoleModel(BaseModel):
    verbose_name = '角色管理'

    role_name = models.CharField(max_length=50, unique=True)
    role_desc = models.CharField(max_length=50, null=True)
    to_user = models.ManyToManyField(to=UserModel, through='UserRoleModel', related_name='to_role',
                                     related_query_name='role')

    class Meta:
        db_table = 'auth_role'


class PermissionModel(BaseModel):
    id = models.IntegerField(primary_key=True)
    app = models.CharField(max_length=50)
    name = models.CharField(max_length=50)
    operate = models.CharField(max_length=50)
    is_valid = models.BooleanField(default=True)
    to_role = models.ManyToManyField(to=RoleModel, through='RolePermissionModel', related_name='to_permission',
                                     related_query_name='permission')

    class Meta:
        db_table = 'auth_permission'
        unique_together = ('name', 'operate')


class UserRoleModel(BaseModel):
    usr = models.ForeignKey(to=UserModel, null=True, on_delete=models.SET_NULL)
    role = models.ForeignKey(to=RoleModel, null=True, on_delete=models.SET_NULL)

    class Meta:
        db_table = 'auth_user_role'


class RolePermissionModel(BaseModel):
    role = models.ForeignKey(to=RoleModel, null=True, on_delete=models.SET_NULL)
    permission = models.ForeignKey(to=PermissionModel, null=True, on_delete=models.SET_NULL)

    class Meta:
        db_table = 'auth_role_permission'


class UserLogModel(models.Model):
    id = models.AutoField(primary_key=True)
    action = models.IntegerField()  # 操作
    target_name = models.CharField(max_length=50, null=True)  # 对象名
    target_id = models.CharField(max_length=50, null=True)  # 对象id
    time = models.DateTimeField(auto_now_add=True)
    user_by = models.ForeignKey(to=UserModel, null=True, on_delete=models.SET_NULL)

    class Action():
        dict = {
            0: '登录',
            1: '登出',
            2: '修改密码',
            11: '新增',
            12: '删除',
            13: '修改',
            14: '执行',
        }

        def output(self, value):
            return self.dict[value] if value in self.dict.keys() else None

    class Meta:
        db_table = 'auth_user_log'
        ordering = ['-time']
